package bim.web.controller.console;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import keter.exception.KeterValidationException;
import keter.util.PathUtil;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import bim.domain.UploadItem;
import bim.service.ImportService;
import bim.web.controller.BaseController;
import util.ConfigConstant;
import util.WebUtil;

@PreAuthorize("hasAnyRole('ADMIN')")
@Controller
@RequestMapping("/console/import")
public class ImportController extends BaseController {
	
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(ImportController.class);

	
	@Autowired
    ImportService service;
	
	/* 系统配置常量 */
	@Autowired
	public ConfigConstant conf;
	
	public static class Views {
		private static final String Prefix = "console/import";
		static final String Index = to_(Prefix) + "index";
		static final String Add = to_(Prefix) + "add";
		static final String Update = to_(Prefix) + "update";
		static final String View = to_(Prefix) + "view";
		static final String Delete = to_(Prefix) + "delete";
	}

	/**
	 * <p>Method ：login
	 * <p>Description : 处理控制台请求
	 * @return 
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 */
	@RequestMapping(value = Routes.Index, method = RequestMethod.GET)
	public String index(Model model) {
        model.addAttribute(new UploadItem());
		return Views.Index;
	}
	
	@RequestMapping(value = Routes.Index, method = RequestMethod.POST)
	public String indexError(Model model) {
		model.addAttribute(new UploadItem());
		return Views.Index;
	}
	
//	@RequestMapping(value = Routes.Add, method = RequestMethod.POST, consumes = MediaTypes.JSON)
//	@ResponseBody
//	public Map<String, String> add(@RequestBody Report report, HttpServletResponse response) throws UnsupportedEncodingException {
//    	Map<String, String> ajaxMap = getAjaxMap();
//    	report.setCreator(getCurrentUser());
//		BeanValidators.validateWithException(validator, report);
//		return ajaxMap;
//	}
	 
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String downLoadPath = PathUtil.getCurrentClassPath(this.getClass())+"/template.xlsx";
		String fileName = "数据导入模板.xlsx";
		WebUtil.makeDownload(request, response, downLoadPath, fileName);
	}
	
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(UploadItem uploadItem,Model model) throws IOException, KeterValidationException{
//        try {
            MultipartFile file = uploadItem.getFileData();
            InputStream inputStream = null;
            if (file.getSize() > 0) {
                inputStream = file.getInputStream();
        		String importFile = ConfigConstant.fileStoreRootPath+"/import.xlsx.temp";
                FileUtils.copyInputStreamToFile(inputStream, new File(importFile));        
//                List<User> list =  XLSUtil.getAccountUserFromXLS(importFile);
//                service.importUser(list);
                model.addAttribute("message", "数据导入成功！");
            }
//        } 
//        catch (Exception e) {
//        	logger.error("数据导入失败:",e);
//            model.addAttribute("message", "导入失败，原因："+e.getMessage());
//        }
        return Views.Index;
    }

}